package org.jcut.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.jcut.bean.Advert;
import org.jcut.data.Data;
import org.jcut.service.AdvertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/advert")
public class AdvertController {
	@Value("${imgsPath}")
	private String path;
	@Autowired
	private AdvertService service;
	@Autowired
	private Data data;
	@RequestMapping("/selectAll")
	public Object selectAll(String location) {
		List<Advert> myList=new ArrayList<Advert>();
		List<Advert> list=service.selectAll();
		for(Advert s:list) {
			if(s.getLocation().equals(location)) {
				myList.add(s);
			}
		}
		data.setMyData(1, "查询成功", myList);
		return data;
	}
	@RequestMapping("/add")
	public Object add(Advert advert,@RequestParam("myImg")MultipartFile file) {
		String imgName=UUID.randomUUID().toString();
		String imgPath=path+imgName+".jpg";
		try {
			advert.setId(UUID.randomUUID().toString());
			advert.setImg("imgs/"+imgName+".jpg");
			file.transferTo(new File(imgPath));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		int i= service.add(advert);
		data.setMyData(i, i>0?"添加成功":"服务器异常", i);
		return data;
	}
	@RequestMapping("/updateDis")
	public Object updateDis(Advert advert) {
		int i= service.updateDis(advert);
		data.setMyData(i, i>0?"修改成功":"服务器异常", i);
		return data;
	}
	@RequestMapping("/selectAdmin")
	public Object selectAdmin(@RequestParam(value="pageNum",required = false)String pageNum,@RequestParam(value="pageSize",required = false) String pageSize) {
		if ((pageNum != null && !("".equals(pageNum))) && (pageSize != null && !("".equals(pageSize)))) {
			PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		PageInfo<Advert> pageInfo = new PageInfo<>(service.selectAdmin());
		
		data.setMyData(1, "查询成功", pageInfo);
		return data;
	}
}
